package cn.wenjie.gd.dao;


import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import cn.wenjie.gd.domain.Collection;
import cn.wenjie.gd.domain.PayType;
import cn.wenjie.gd.util.CollectionPage;
import cn.wj.base.dao.BaseDaoImp;
import cn.wj.base.util.Page;

public class CollectionDaoImp extends BaseDaoImp<Collection, Integer> implements CollectionDao {

	@Override
	public Class<Collection> getEntryClass() {
		return Collection.class;
	}

	@Override
	public List<PayType> getAllPayType() {
		// TODO Auto-generated method stub
		return query(" SELECT p.id,p.paymethod FROM paytype p ",PayType.class);
	}

	@Override
	public Page getPage(CollectionPage page) {
 
		StringBuffer sqlbody = new StringBuffer();
		List list = new ArrayList();
		sqlbody.append("  FROM  collection c WHERE 1=1 ");
		if (page.getPayType()!=null) {
			sqlbody.append(" AND c.payType=? ");
			list.add(page.getPayType());
		}
		if (page.getMark()!=null) {
			sqlbody.append(" AND c.mark="+page.getMark()+" ");
			//list.add(page.getMark());
		}
		if (page.getDate()!= null) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			sqlbody.append("  AND  c.date>='"+format.format(page.getDate())+"' ");
		}if (page.getDateEnd()!= null) {
			SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
			sqlbody.append("  AND  c.date<='"+format.format(page.getDateEnd())+"' ");
		}

		StringBuffer getCountSql = new StringBuffer();
		StringBuffer sql = new StringBuffer();

		getCountSql.append(" SELECT COUNT(*) ");
		getCountSql.append(sqlbody);
		sql.append(" SELECT * ");
		sql.append(sqlbody);
		sql.append(" LIMIT ?,? ");

		int count = queryForInt(getCountSql.toString(), list.toArray());
		page.setTotalRecord(count);
		list.add(page.getStartIndex());
		list.add(page.getPageSize());

		List Resultlist = query(sql.toString(), getEntryClass(), list.toArray());
		page.setResult(Resultlist);
		return page;
	}
	
	public List<Collection> todayGrade(){
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
		String sql="SELECT c.date ,SUM(amount) amount,SUM(mcost) mcost FROM collection c WHERE c.date='"+format.format(new Date())+"' ";
		return  query(sql.toString(), getEntryClass());	
	}

}
